import {Subject} from 'rxjs';
import {Component, OnInit, ViewEncapsulation, ViewChild,} from '@angular/core';
import {Router, ActivatedRoute, Params} from '@angular/router';

import {SeedInfiniteScroll} from "@shared/components/infinite-scroll/seed-infinite-scroll/seed-infinite-scroll.component";
import {ToolbarService} from "@shared/components/toolbar/toolbar.service";
import {ToolsService} from "@shared/service/tools/tools.service";
import {VideoService} from "../video.service";
import {VideoRespVO} from "@interface/index";


@Component({
  selector: 'app-video-more',
  templateUrl: './video-more.component.html',
  styleUrls: ['./video-more.component.scss'],
  encapsulation: ViewEncapsulation.None
})

export class VideoMoreComponent implements OnInit {
  public category: Array<VideoRespVO> = [];
  public categoryId: number;
  public currentCategory: string;
  public haveData = true;
  public page = 1;
  public ngUnsubscribe: Subject<void> = new Subject<void>();

  @ViewChild(SeedInfiniteScroll) infiniteScroll;

  constructor(public route: ActivatedRoute,
              public router: Router,
              public videoService: VideoService,
              public toolbarService: ToolbarService,
              public toolsService: ToolsService) {
  }

  onScroll() {
    this.toolsService.showLoading();
    this.videoService.getCategory(this.categoryId, this.page)
      .debounceTime(800)
      .subscribe(res => {
        this.page++;
        this.toolsService.hideLoading();
        const category = res.data.list;
        this.infiniteScroll.complete();
        if (res.result === '0' && category.length > 0) {
          this.haveData = true;
          !res.data.hasNextPage && this.infiniteScroll.enable(false);
          this.category = category;
        }
      });
  }

  ngOnInit() {
    this.currentCategory = this.videoService.currentCategory;
    this.route.params
      .takeUntil(this.ngUnsubscribe)
      .do(() => this.toolbarService.unfoldNav())
      .subscribe((params: Params) => {
        this.categoryId = params['categoryId'];
        this.onScroll();
        this.currentCategory = this.videoService.currentCategory;
      });
  }
}
